package com.infoland.afanmall.base.util.okhttp;


import android.app.Activity;

import com.alibaba.fastjson.JSONObject;
import com.infoland.afanmall.base.util.CONST;
import com.infoland.afanmall.base.util.CacheKit;
import com.infoland.afanmall.base.util.LogKit;
import com.infoland.afanmall.base.util.ToolsKit;
import com.infoland.afanmall.model.eventBus.main.InternetCloseBus;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.Callback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.vondear.rxtools.RxNetTool;

import org.greenrobot.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.Date;

import okhttp3.Call;
import okhttp3.ResponseBody;

/**
 * @author 王永吉
 * @date 2018/8/2 8:41
 * OkHttpKit 网络请求类 二次封装
 * ErrorInternet
 * （断网 -1） (超时 -1)
 * （未登录 401）(请求地址错误 404)（JSON参数错误 400) (参数类错误 415)
 * (服务端错误 500)
 * (手动取消  （暂时不做操作）)
 * Success200
 * （请求成功 200）
 */
public class OkHttpKit {
    Error error;
    ErrorCancel errorCancel;
    ErrorInternet errorInternet;
    Error400 error400;
    Error404 error404;
    Error500 error500;
    Success200 success200;
    Error401 error401;

    public OkHttpKit() {

    }

    public OkHttpKit sendAll(Success200 success200,
                             Error401 error401,
                             ErrorInternet error_1,
                             Error500 error500,
                             Error400 error400,
                             Error404 error404,
                             ErrorCancel errorCancle
    ) {
        this.errorInternet = error_1;
        this.error400 = error400;
        this.error404 = error404;
        this.error500 = error500;
        this.success200 = success200;
        this.errorCancel = errorCancle;
        this.error401 = error401;
        return this;
    }

    //
    public OkHttpKit send(Success200 success200, Error401 error401,
                          Error error) {
        this.error = error;
        this.success200 = success200;
        this.error401 = error401;
        return this;
    }

    //
    public OkHttpKit send(Success200 success200, Error error) {
        this.error = error;
        this.success200 = success200;
        return this;
    }

    //
    public OkHttpKit send(Success200 success200, Error401 error401,
                          Error error, ErrorInternet errorInternet) {
        this.error = error;
        this.success200 = success200;
        this.error401 = error401;
        this.errorInternet = errorInternet;
        return this;
    }

    public OkHttpKit post(String url, JSONObject params, Object tag) {
        showTime();
        String URL = CONST.HTTP + url;
        LogKit.E("URL ---->    ", "  " + URL);
        LogKit.E("params ---->    ", "  " + params);
        if (RxNetTool.isAvailable(CacheKit.APP_CONTEXT)) {
            OkGo.<String>post(URL).upJson(params.toJSONString()).tag(tag).execute(getCall());
        } else {
            if (errorInternet != null) {
                errorInternet.onError("网络断开.....");
            }
        }
        return this;
    }

    public OkHttpKit get(String url, JSONObject params, Activity tag) {
        showTime();
        String URL = CONST.HTTP + url;
        LogKit.E("URL ---->   ", "  " + URL);
        LogKit.E("params ---->   ", "  " + params);
        if (RxNetTool.isAvailable(CacheKit.APP_CONTEXT)) {
            OkGo.<String>get(URL).tag(tag).execute(getCall());
        } else {
            if (errorInternet != null) {
                errorInternet.onError("网络断开.....");
            }
        }
        OkGo.<String>get(URL).tag(tag).execute(getCall());
        return this;
    }

    private void showTime() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
        Date date = new Date();
        LogKit.E("发送请求时间---->   ", "  " + simpleDateFormat.format(date));
    }


    private Callback<String> getCall() {
        return new Callback<String>() {
            @Override
            public String convertResponse(okhttp3.Response response) throws Throwable {
//                LogKit.E("convertResponse ---->   ", "convertResponse");
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
                Date date = new Date(response.sentRequestAtMillis());
                LogKit.E("convertResponse  请求返回时间---->   ", "  " + simpleDateFormat.format(date));
//                LogKit.E("convertResponse  code---->   ", "  " + response.code());
//                LogKit.E("convertResponse  message ---->   ", "  " + response.message());
                ResponseBody body = response.body();
//                if (success200 != null) {
//                }
                return body.string();
            }

            @Override
            public void onSuccess(Response<String> response) {
                String body = response.body();
                int code1 = response.code();
                LogKit.E("onSuccess  code---->   ", "  " + code1);
                if (code1 == 200) {
                    if (success200 != null) {
                        LogKit.E("200 ---->   ", "  200   " + body);
                        success200.onSuccess(body);
                    }
                }
                if (code1 == 401) {
                    if (error401 != null) {
                        LogKit.E("error401 ---->   ", "  error401   " + body);
                        error401.onError(response.message());
                    }
                }
            }

            @Override
            public void onError(Response<String> response) {
                LogKit.E("aaaa ---->   ", "  " + response.message());
                LogKit.E("aaaa ---->   ", "  " + response.code());
                Call rawCall = response.getRawCall();
                int code = response.code();
                if (rawCall != null) {
                    if (rawCall.isCanceled()) {
                        if (errorCancel != null) {
                            LogKit.E("errorCancel ---->   ", "  errorCancel");
                            errorCancel.onError("手动取消");
                        }
                        if (error != null) {
                            LogKit.E("errorCancel ---->   ", "  errorCancel");
                            error.onError("手动取消");
                        }
                        return;
                    }
                }
                switch (code) {
//                    case 401:
//                        if (error401 != null) {
//                            LogKit.E("401 ---->   ", "  401");
//                            error401.onError(response.message());
//                        }
//                        LogKit.E("   ", "  " + "  ");
//                        break;
                    case -1:
                        ToolsKit.sendMessage(new InternetCloseBus());
                        if (errorInternet != null) {
                            errorInternet.onError(response.message());
                        }
                        break;
                    case 400:
                        if (error != null) {
                            LogKit.E("error ---->   ", "  error");
                            error.onError(response.message());
                        }
                        if (error400 != null) {
                            LogKit.E("error400 ---->   ", "  error400");
                            error400.onError(response.message());
                        }
                        break;
                    case 404:
                        if (error != null) {
                            LogKit.E("error ---->   ", "  error");
                            error.onError(response.message());
                        }
                        if (error404 != null) {
                            LogKit.E("error404 ---->   ", "  error404");
                            error404.onError(response.message());
                        }
                        LogKit.E("   ", "  " + "  ");
                        break;
                    case 500:
                        if (error != null) {
                            LogKit.E("error ---->   ", "  error");
                            error.onError(response.message());
                        }
                        if (error500 != null) {
                            LogKit.E("error500 ---->   ", "  error500");
                            error500.onError(response.message());
                        }
                        break;

                }
            }


            @Override
            public void onStart(Request<String, ? extends Request> request) {
            }


            @Override
            public void onCacheSuccess(Response<String> response) {
//                LogKit.E("onCacheSuccess ---->   ", "onCacheSuccess");

            }

            @Override
            public void onFinish() {
//                LogKit.E("onFinish ---->   ", "onFinish");

            }

            @Override
            public void uploadProgress(Progress progress) {

            }

            @Override
            public void downloadProgress(Progress progress) {
            }

        }

                ;
    }
}
